package com.richard.dev.common.activity.printer;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.richard.dev.common.R;
import com.richard.library.basic.util.ObjectUtil;
import com.richard.library.bluetooth.SelectBleDialog;
import com.richard.library.port.connect.PortControl;
import com.richard.library.port.connect.PortManager;
import com.richard.library.port.connect.exception.PortException;
import com.richard.library.printer.command.DZELabelCmd;
import com.richard.library.printer.command.PrinterCmd;
import com.richard.library.printer.command.PrinterCmdUtil;
import com.richard.library.printer.enumerate.Align;
import com.richard.library.printer.enumerate.EllipsizeMode;
import com.richard.library.printer.enumerate.TicketSpec;
import com.richard.library.printer.utils.PrintImageUtil;
import com.richard.library.printer.utils.PrintParams;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

@Route(path = "/test/printer")
public class TestPrinterActivity extends AppCompatActivity {

    private View btn_select_ble;
    private View btn_test_print;
    private View btn_test_serial;
    private View btn_test_honeywell_print;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_printer);

        //绑定控件
        btn_select_ble = findViewById(R.id.btn_select_ble);
        btn_test_print = findViewById(R.id.btn_test_print);
        btn_test_serial = findViewById(R.id.btn_test_serial);
        btn_test_honeywell_print = findViewById(R.id.btn_test_honeywell_print);

        btn_select_ble.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSelectBleWindow(v);
            }
        });

        btn_test_print.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                startPrint("512",null,generatorPrintData());
                startPrint("192.168.3.200","9100",generatorPrintData());

//                UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
//                HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
//                Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
//                while (deviceIterator.hasNext()) {
//                    UsbDevice usbDevice = deviceIterator.next();
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                        Log.d("testtt", String.format("%s[%s][productId = %s]", usbDevice.getManufacturerName(), usbDevice.getDeviceName(), usbDevice.getProductId()));
//                    } else {
//                        Log.d("testtt", String.format("%s[%s][productId = %s]", usbDevice.getDeviceName(), usbDevice.getDeviceName(), usbDevice.getProductId()));
//                    }
//                }
            }
        });


        btn_test_serial.setOnClickListener((v) -> {
            new Thread(() -> {
                try {
                    PortControl printer = PortManager.get().connectSerialPort("/dev/ttyS3", 9600);
                    int count = 10;
                    while (count > 0) {
                        byte[] buffer = new byte[64];
                        printer.read(buffer);
                        Log.d("testtt", new String(buffer, 0, buffer.length));
                        count--;

                        try {
                            Thread.sleep(1500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (PortException e) {
                    e.printStackTrace();
                }
            }).start();
        });

        btn_test_honeywell_print.setOnClickListener((v) -> {
            new Thread(this::testHoneywellLabelPrint).start();
        });
    }

    private void showSelectBleWindow(View v) {
        SelectBleDialog.startForResult(getSupportFragmentManager(),true, device -> {
            BluetoothDevice bleDevice = device.getDevice();
            startPrint(bleDevice.getAddress(),null, generatorPrintData());
        });
        startPrint("DC:0D:30:38:1C:DB",null,generatorPrintData());
    }

    /**
     * 测试霍尼韦尔标签打印
     */
    private void testHoneywellLabelPrint() {
        try {

            DZELabelCmd cmd = new DZELabelCmd();
            cmd.PRN_AddTextToLabel("测试哈哈哈", 100, 100);
            cmd.PRN_PrintLabel(1);

            PortControl portControl = PortManager.get().connectUSBPort(getApplicationContext(), "65040",null);
            portControl.write(cmd.getCmdResult());

            Thread.sleep(1000);

            //端口连接
            portControl.disconnect();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试打印
     */
    private PrintParams generatorPrintData() {
        PrintParams printParams = new PrintParams(TicketSpec.SPEC_58);
        printParams.add("消费小票", 1, false, Align.CENTER);
        printParams.addRow(0, String.format("单号:%s", "AD123213212321231231223434343432"));
        printParams.addSplitLine(0, true);

        //第一种
        printParams.addRow("名称", "数量", "单价", "小计");
        printParams.addRow(EllipsizeMode.ELLIPSIS, "青椒肉丝炒饭", "1", "0.99", "0.99");
        printParams.addRow(EllipsizeMode.ELLIPSIS, "牛排4人套餐", "1", "0.99", "0.99");
        printParams.addRow(EllipsizeMode.ELLIPSIS, "青椒肉丝炒饭", "1", "0.99", "0.99");
        printParams.addRow(EllipsizeMode.ELLIPSIS, "牛排4人套餐", "1", "0.99", "0.99");
        printParams.addSplitLine(0, true);
        printParams.addNextRow();
        printParams.add(PrintImageUtil.getPrintBitmapData(BitmapFactory.decodeResource(getResources(),R.mipmap.icon_loading_logo),200,200));

        Log.d("testtt",printParams.toString());


        //第二种
//        int fontSize = 0;
//        float[] widthWeigh = new float[]{2F, 1, 1, 1};
//        printParams.addRow(
//                fontSize
//                , widthWeigh
//                , new ColumnItem("名称", Align.LEFT)
//                , new ColumnItem("数量", Align.LEFT)
//                , new ColumnItem("单价", Align.LEFT)
//                , new ColumnItem("合计", Align.RIGHT)
//        );
//
//        printParams.addRow(
//                fontSize
//                , widthWeigh
//                , new ColumnItem("土豆肉丝土豆肉丝土豆肉丝土豆肉丝土豆肉丝土豆肉丝土豆肉丝土豆肉丝土豆肉丝土豆肉丝土豆肉丝土豆肉丝", false, EllipsizeMode.COLUMN_LINE, Align.LEFT)
//                , new ColumnItem("10", false, EllipsizeMode.COLUMN_LINE, Align.LEFT)
//                , new ColumnItem("9990099900999009990099900", false, EllipsizeMode.ELLIPSIS, Align.LEFT)
//                , new ColumnItem("0.99", false, EllipsizeMode.COLUMN_LINE, Align.RIGHT)
//        );
//
//        printParams.addRow(
//                fontSize
//                , widthWeigh
//                , new ColumnItem("青椒土豆肉丝", false, EllipsizeMode.COLUMN_LINE, Align.LEFT)
//                , new ColumnItem("100", false, EllipsizeMode.COLUMN_LINE, Align.LEFT)
//                , new ColumnItem("0.99", false, EllipsizeMode.COLUMN_LINE, Align.LEFT)
//                , new ColumnItem("", false, EllipsizeMode.COLUMN_LINE, Align.RIGHT)
//        );

        return printParams;
    }

    /**
     * 开始打印
     *
     * @param printDataList 必填 打印数据
     * @return 是否打印成功
     */
    public void startPrint(String linkTarget, String port, final List<byte[]> printDataList) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //连接打印机并打印
                    PortControl printer = null;

                    if (ObjectUtil.isNotEmpty(linkTarget) && ObjectUtil.isNotEmpty(port)) {
                        printer = PortManager.get().connectNetPort(linkTarget, ObjectUtil.toInt(port));
                    }else{
                        printer = PortManager.get().connectUSBPort(getApplicationContext(), linkTarget,null);
//                        printer = PortManager.get().connectBTPort(linkTarget);
                    }

                    //重置复位打印机
                    printDataList.add(0, PrinterCmdUtil.resetPrinter());

                    //打印并换行
                    printDataList.add(PrinterCmdUtil.printLineFeed());

                    //进纸切割
                    printDataList.add(PrinterCmdUtil.feedPaperCutPartial());

                    //重置复位打印机
                    printDataList.add(0, PrinterCmdUtil.resetPrinter());

                    //写入打印内容数据
                    printer.write(printDataList);

                    //端口连接
                    printer.disconnect();
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        PortManager.get().disconnectAll();
        super.onDestroy();
    }
}